package org.fuxia.im.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.Map.Entry;
import java.util.Timer;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.fuxia.im.common.AquaBarTabbedPaneUI;
import org.fuxia.im.common.ClientConst;
import org.fuxia.im.common.ClientContext;
import org.fuxia.im.common.CommonDialog;
import org.fuxia.im.common.IconManager;
import org.fuxia.im.core.ECMessageType;
import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.entities.User;
import org.tony.common.ui.CommonFrame;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@SuppressWarnings({"unchecked","rawtypes"})
public class Main extends CommonFrame implements ComponentListener{

	private static final long serialVersionUID = 1L;
	private final JPanel contentPane;
	private final JTextField friend;
	private final JMenuItem exitMenuItem;
	private JTree tree  ;
	private JTree friendList ;
	private JPopupMenu setMenu ;
	private JButton setting  ;
	private MyDefaultMutableTreeNode groupRootNode ;
	
	private JPopupMenu friendPopMenu ;
	
	/**
	 * Create the frame.
	 */
	public Main(final Map<String, List<Object>> map) {
		super() ;

		this.addComponentListener(this) ;
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(800, 50, 279, 560);
		setTitle("Live Chat");

		contentPane = new JPanel();
		contentPane.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JPanel panel = new JPanel();
		panel.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(new BorderLayout(0, 0));
		panel.setOpaque(false);

		JPanel panel_1 = new JPanel();
		panel_1.setOpaque(false);
		panel_1.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel.add(panel_1, BorderLayout.NORTH);
		panel_1.setLayout(new BorderLayout(0, 0));

		JLabel lblNewLabel_1 = new JLabel("");
		ImageIcon icon = null ;
		URL imageUrl = Thread.currentThread().getContextClassLoader().getResource(ClientContext.getLoginUser().getImagePath());
		if(imageUrl == null){
			icon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("images/tangling.jpg"));
		}else {
			icon = new ImageIcon(imageUrl);
		}
		lblNewLabel_1.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		lblNewLabel_1.setIcon(icon);
		panel_1.add(lblNewLabel_1, BorderLayout.WEST);

		JPanel panel_10 = new JPanel();
		panel_10.setOpaque(false);
		panel_10.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel_1.add(panel_10, BorderLayout.CENTER);
		panel_10.setLayout(new BorderLayout(0, 0));

		JPanel panel_11 = new JPanel();
		panel_11.setOpaque(false);
		panel_10.add(panel_11, BorderLayout.CENTER);
		panel_11.setLayout(null);

		JComboBox status = new JComboBox();
		status.setModel(new DefaultComboBoxModel(new String[] { "在线", "隐身",
				"离开", "忙碌", "离线" }));
		status.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		status.setBounds(10, 10, 54, 21);
		panel_11.add(status);

		JLabel nickname = new JLabel(ClientContext.getLoginUser().getNickName());
		nickname.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		nickname.setBounds(64, 13, 100, 15);
		panel_11.add(nickname);

		JLabel spitball = new JLabel(ClientContext.getLoginUser().getPersonNote());
		spitball.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		spitball.setBounds(10, 41, 188, 19);
		panel_11.add(spitball);

		JPanel panel_12 = new JPanel();
		panel_10.add(panel_12, BorderLayout.EAST);
		panel_12.setLayout(new BorderLayout(0, 0));
		panel_12.setOpaque(false);


		JPanel panel_2 = new JPanel();
		panel_2.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel.add(panel_2, BorderLayout.CENTER);
		panel_2.setLayout(new BorderLayout(0, 0));
		panel_2.setOpaque(false);

		JPanel panel_4 = new JPanel();
		panel_4.setOpaque(false);
		panel_4.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel_2.add(panel_4, BorderLayout.NORTH);
		panel_4.setLayout(new BorderLayout(0, 0));

		friend = new JTextField();
		friend.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel_4.add(friend, BorderLayout.CENTER);
		friend.setColumns(10);

		JButton searchBtn = new JButton("");
		searchBtn.setMargin(new Insets(1, 2, 1, 2));
		searchBtn.setIcon(IconManager.getIcon("images/search_normal.png"));
		searchBtn.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel_4.add(searchBtn, BorderLayout.EAST);

		JPanel panel_5 = new JPanel();
		panel_5.setOpaque(false);
		panel_5.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel_2.add(panel_5, BorderLayout.CENTER);
		panel_5.setLayout(new BorderLayout(0, 0));
		panel_5.setBorder(null);

		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setOpaque(false);
		tabbedPane.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel_5.add(tabbedPane, BorderLayout.CENTER);
		tabbedPane.setUI(new AquaBarTabbedPaneUI()) ;
		JPanel panel_6 = new JPanel();
		panel_6.setOpaque(false);
		panel_6.setBorder(null);
		panel_6.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		tabbedPane.addTab("联系人", null, panel_6, null);
		panel_6.setLayout(new BorderLayout(0, 0));

		friendList	 = new JTree();
		final MyTreeCellRender myTreeCellRender = new MyTreeCellRender() ;
		friendList.setToggleClickCount(1);
		friendList.putClientProperty("JTree.lineStyle", "None" );
		friendList.setCellRenderer(myTreeCellRender) ;
		friendList.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		friendList.setModel(new DefaultTreeModel(
				new DefaultMutableTreeNode("JTree") {

					private static final long serialVersionUID = 1L;

					{
						Iterator ite = map.entrySet().iterator() ;
						MyDefaultMutableTreeNode groupnode ;
						String[] groups = new String[map.entrySet().size()] ;
						int k = 0 ;
						while(ite.hasNext()){
							Entry entry = (Entry) ite.next() ;
							String key = entry.getKey().toString() ;
							System.out.println(key);
							String[] group = key.split("#") ;
							JSONArray value = (JSONArray) entry.getValue();
							groupnode = new MyDefaultMutableTreeNode(group[1]) ;
							groupnode.setGroupId(group[0]) ;
							for(int i=0; i<value.size();i++){
								JSONArray o = (JSONArray) value.get(i);
								MyDefaultMutableTreeNode friend = new MyDefaultMutableTreeNode(
										o.get(1));
								friend.setUserId(o.get(0).toString());
								friend.setNickname(o.get(1).toString());
								friend.setImageUrl(o.get(4).toString());
								groupnode.add(friend) ;
							}
							add(groupnode) ;
							
							groups[k] = key;
							k++ ;
						}
						ClientContext.getContext().put("groups", groups) ;
					}
				}
				));
		friendList.setRootVisible(false);
		panel_6.add(friendList, BorderLayout.CENTER);
		panel_6.setOpaque(false);
		
		friendPopMenu = createFriendPopMenu();
		

		MouseListener ml = new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				super.mouseClicked(e);
				MyDefaultMutableTreeNode node = (MyDefaultMutableTreeNode)friendList.getLastSelectedPathComponent() ;
				if(node != null && node.isLeaf() && node.getLevel() == 2){
					if(e.getButton() == MouseEvent.BUTTON1) {
							if(e.getClickCount()==2){
								createAndShowChatWindow(node) ;
							}
					}else if(e.getButton() == MouseEvent.BUTTON3) {
						if(friendPopMenu==null){
							friendPopMenu = createFriendPopMenu() ;
						}
						friendPopMenu.show(friendList, e.getX(), e.getY()) ;
					}
				}
			}
		};
		friendList.addMouseListener(ml) ;

		JPanel group = new JPanel();
		group.setOpaque(false);
		group.setBorder(null);
		group.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		tabbedPane.addTab("群/讨论组", null, group, null);
		group.setLayout(new BorderLayout(0, 0));

		tree = new JTree();
		tree.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		MyTreeCellRender cellRender = new MyTreeCellRender();
		tree.setCellRenderer(cellRender) ;
		tree.setToggleClickCount(1);
		tree.putClientProperty("JTree.lineStyle", "None" );
		tree.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				final MyDefaultMutableTreeNode node = (MyDefaultMutableTreeNode)tree.getLastSelectedPathComponent() ;
				if(e.getButton() == MouseEvent.BUTTON1) {
					if(node != null && node.isLeaf() && node.getLevel() >= 2){
						if(e.getClickCount()==2 ){
							String groupId = node.getGroupId() ;
							Object obj = ClientContext.getValue(groupId);
							GroupChat gChat = null ;
							if(obj!=null && obj instanceof GroupChat){
								gChat = (GroupChat)obj;
								gChat.setState(JFrame.NORMAL);
							}else {
								gChat = new GroupChat() ;
								ClientContext.putValue(groupId, gChat);
								gChat.showGroupChatWindow(groupId);
							}
						}
					}
				}else if(e.getButton() == MouseEvent.BUTTON3) {
					JPopupMenu jpm = new JPopupMenu();
					jpm.setBorder(new LineBorder(Color.LIGHT_GRAY,1,true));
					JMenuItem sendMessage = new JMenuItem("发送消息");
					sendMessage.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							String groupId = node.getGroupId() ;
							Object obj = ClientContext.getValue(groupId);
							GroupChat gChat = null ;
							if(obj!=null && obj instanceof GroupChat){
								gChat = (GroupChat)obj;
								gChat.setState(JFrame.NORMAL);
							}else {
								gChat = new GroupChat() ;
								ClientContext.putValue(groupId, gChat);
								gChat.showGroupChatWindow(groupId);
							}
						}
					});
					jpm.add(sendMessage);
					jpm.addSeparator();
					final boolean isOwner = node.getOwnerId().equals(ClientContext.getLoginUser().getUserCode()) ;
					JMenuItem groupOp = new JMenuItem(isOwner?"解散群组":"退出群组");
					groupOp.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							String message = isOwner?"是否解散该群？":"是否退出该群？";
							int result = JOptionPane.showConfirmDialog(tree, message) ;
							if(result== JOptionPane.OK_OPTION) {
								ECPacket p = new ECPacket() ;
								p.setMessageType(ECMessageType.GROUP_OP.name()) ;
								p.setFrom(ClientContext.getLoginUser().getUserCode()) ;
								p.addParam("groupId", node.getGroupId()) ;
								if(isOwner) {
									p.addParam("option", "dismissGroup") ;
								}else {
									p.addParam("owner", node.getOwnerId()) ;
									p.addParam("option", "exitGroup") ;
									p.addParam("userCode", ClientContext.getLoginUser().getUserCode()) ;
								}
								try {
									ClientContext.putValue(ClientConst.CURRENT_REQUESTOR, Main.this);
									ClientContext.getContext().getClient().sendMessage(p);
									((DefaultTreeModel)tree.getModel()).removeNodeFromParent(node);
									ClientContext.removeChatGroupById(node.getUserId()) ;
								} catch (Exception e1) {
								}
							}
						}
					});
					groupOp.setIcon(IconManager.getIcon("images/group_delete.png")) ;
					jpm.add(groupOp) ;
					
					//jpm.setPopupSize(152, jpm.getComponentCount()*25) ;
					jpm.show(tree, e.getX(), e.getY()) ;
				}
			}
		});
		
		group.add(tree, BorderLayout.CENTER);
		tree.setRootVisible(false);


		JPanel bottomToolBarPannel = new JPanel(){
			private static final long serialVersionUID = 1L;

			@Override
			protected void paintComponent(Graphics g) {
				super.paintComponent(g);
				Graphics2D g2d = (Graphics2D)g ;
				g2d.setColor(new Color(88,183,237));
				g2d.drawLine(0, 0, getWidth(), 0) ;
			}
		};
		bottomToolBarPannel.setOpaque(false);
		bottomToolBarPannel.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel.add(bottomToolBarPannel, BorderLayout.SOUTH);
		GridBagLayout gbl_panel_3 = new GridBagLayout();
		bottomToolBarPannel.setLayout(gbl_panel_3);

		JButton findFridBtn = new JButton();
		findFridBtn.setContentAreaFilled(false);
		findFridBtn.setOpaque(false);
		findFridBtn.setBorder(new EmptyBorder(-1,0,0,0));
		// findFridBtn.setBorder(new EmptyBorder(new Insets(0, 0, 0, 0)));
		// findFridBtn.setBackground(new Color(2, 2, 2));
		findFridBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object obj = ClientContext.getContext().get("findFrame") ;
				FindFriend find = null ;
				if(obj != null && obj instanceof FindFriend){
					find = (FindFriend)obj ;
					find.setState(JFrame.NORMAL) ;
				}else{
					find = new FindFriend() ;
					ClientContext.getContext().put("findFrame", find) ;
					find.setVisible(true) ;
				}
			}
		});
		findFridBtn.setIcon(IconManager.getIcon("images/find.png"));
		GridBagConstraints gbc_findFridBtn = new GridBagConstraints();
		gbc_findFridBtn.insets = new Insets(2, 2, 2, 3);
		gbc_findFridBtn.gridx = 0;
		gbc_findFridBtn.gridy = 0;
		gbc_findFridBtn.ipady = -4 ;
		gbc_findFridBtn.ipadx = -4 ;
		gbc_findFridBtn.weightx = 0 ;
		gbc_findFridBtn.weighty = 0 ;
		bottomToolBarPannel.add(findFridBtn, gbc_findFridBtn);
		
		setting = new JButton() ;
		setting.setIcon(IconManager.getIcon("images/setting.png")) ;
		setting.setContentAreaFilled(false);
		setting.setOpaque(false);
		setting.setBorder(new EmptyBorder(-3,0,0,0));
		GridBagConstraints settingGBC = new GridBagConstraints();
		gbc_findFridBtn.insets = new Insets(0, 0, 2, 3);
		settingGBC.gridx = 1;
		settingGBC.gridy = 0;
		settingGBC.ipady = -4 ;
		settingGBC.ipadx = -4 ;
		settingGBC.weightx = 0 ;
		settingGBC.weighty = 0 ;
		bottomToolBarPannel.add(setting, settingGBC);
		setting.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				int height = setMenu.getHeight() ;
				if(height==0) {
					height = (119/5)* setMenu.getComponentCount() + 4; 
				}
				setMenu.show(setting, 0, 0-height);
			}
		});
		
		JLabel fillLab = new JLabel() ;
		GridBagConstraints labGbc = new GridBagConstraints();
		labGbc.fill = GridBagConstraints.HORIZONTAL;
		labGbc.weightx = 1 ;
		labGbc.gridx = 2;
		labGbc.gridy = 0;
		bottomToolBarPannel.add(fillLab, labGbc);


		setMenu = new JPopupMenu();

		JMenuItem infoMenuItem = new JMenuItem("个人资料");
		infoMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				IndividualInfo info = new IndividualInfo((User)ClientContext.getValue(ClientConst.CURRENT_USER)) ;
				ClientContext.getContext().put("individualInfo", info) ;
				info.setVisible(true) ;
			}
		});
		infoMenuItem.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		infoMenuItem.setIcon(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("images/info.jpg")));
		setMenu.add(infoMenuItem);

		JMenuItem friManMenuItem = new JMenuItem("好友管理");
		friManMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				 FriendManage manage = new FriendManage() ;
				 ClientContext.getContext().put("friendManage", manage) ;
				 manage.setVisible(true) ;
			}
		});
		friManMenuItem.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		friManMenuItem.setIcon(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("images/manage.jpg")));
		setMenu.add(friManMenuItem);

		JMenuItem updPwdMenuItem = new JMenuItem("修改密码");
		updPwdMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ModifyPwd modifyPwd = new ModifyPwd() ;
				modifyPwd.setVisible(true) ;
			}
		});
		updPwdMenuItem.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		updPwdMenuItem.setIcon(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("images/modify.jpg")));
		setMenu.add(updPwdMenuItem);

		
		JMenuItem groupManage = new JMenuItem("创建群组") ;
		groupManage.setIcon(IconManager.getIcon("images/group_add.png")) ;
		groupManage.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		setMenu.add(groupManage);
		groupManage.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				GroupManager gm = new GroupManager() ;
				gm.showDialog();
			}
		});

		exitMenuItem = new JMenuItem("退出");
		exitMenuItem.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		exitMenuItem.setIcon(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("images/exit.jpg")));
		exitMenuItem.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				hanlderCloseEvent();
			}
		});
		setMenu.add(exitMenuItem);
		
		setContent(contentPane);
		

	}
	
	public void deleteGroupNode(final String groupId) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				DefaultTreeModel dm = ((DefaultTreeModel)tree.getModel()) ;
				int count = dm.getChildCount(groupRootNode);
				for(int i=0;i<count;i++) {
					MyDefaultMutableTreeNode node = (MyDefaultMutableTreeNode)groupRootNode.getChildAt(i);
					if(node.getGroupId().equals(groupId)) {
						dm.removeNodeFromParent(node) ;
						break;
					}
				}
				ClientContext.removeChatGroupById(groupId) ;
			}
		});
	}

	private JPopupMenu createFriendPopMenu() {
		JPopupMenu jp = new JPopupMenu();
		JMenuItem sendMessage = new JMenuItem("发送即时消息");
		sendMessage.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				MyDefaultMutableTreeNode node = (MyDefaultMutableTreeNode)friendList.getLastSelectedPathComponent() ;
				createAndShowChatWindow(node);
			}
		});
		sendMessage.setIcon(IconManager.getIcon("images/sendmsg.png")) ;
		JMenuItem delUser = new JMenuItem("删除好友");
		delUser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				MyDefaultMutableTreeNode node = (MyDefaultMutableTreeNode)friendList.getLastSelectedPathComponent() ;
				MyDefaultMutableTreeNode parent = (MyDefaultMutableTreeNode)node.getParent() ;
				String groupKey = parent.getGroupId() + "#" + parent.getUserObject() ;
				int r = JOptionPane.showConfirmDialog(Main.this, "确认删除该好友？");
				if(r == JOptionPane.OK_OPTION) {
					doDelUser(node.getUserId(), groupKey, Main.this, CommonDialog.createModelWaitDialog(Main.this)) ;
				}
			}
		});
		delUser.setIcon(IconManager.getIcon("images/deluser.png")) ;
		jp.add(sendMessage);
		jp.add(delUser);
		return jp;
	}
	
	/**
	 * 删除好友
	 * @param userId 		好友编号
	 * @param curReqWindow	当前发起请求的窗体
	 * @param waitingDialog 等待窗体
	 */
	public static void doDelUser(String userId,String groupKey,Component curReqWindow,Component waitingDialog) {
		ClientContext.putValue(ClientConst.CURRENT_REQUESTOR, curReqWindow) ;
		ECPacket packet = new ECPacket() ;
		packet.setMessageType("USER_MANAGE") ;
		packet.addParam("groupKey", groupKey) ;
		packet.addParam("option", "delUser") ;
		packet.setFrom(ClientContext.getLoginUser().getUserCode()) ;
		packet.addParam("del_user_code", userId);
		if(waitingDialog!=null) {
			ClientContext.putValue(ClientConst.CURRENT_WAITING_DIALOG, waitingDialog);
			new Timer().schedule(new TimerTask() {
				public void run() {
					ClientContext.getValue(ClientConst.CURRENT_WAITING_DIALOG, JDialog.class).dispose() ;
					CommonDialog.showErrorMessageDialog(ClientContext.getValue(ClientConst.MAIN_WINDOW, Main.class), 
							"删除好友失败！");
				}
			}, 5*60*1000) ;
		}
		try {
			ClientContext.getContext().getClient().sendMessage(packet);
			if(waitingDialog!=null) {
				waitingDialog.setVisible(true);
			}
		} catch (Exception e) {
			CommonDialog.showErrorMessageDialog(ClientContext.getValue(ClientConst.MAIN_WINDOW, Main.class), 
					"请检查网络连接");
		}
		
	}
	
	public void updateFriendList(){
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				MyDefaultMutableTreeNode node = (MyDefaultMutableTreeNode)friendList.getLastSelectedPathComponent();
				((DefaultTreeModel)friendList.getModel()).removeNodeFromParent(node);
			}
		});
	}

	public void componentResized(ComponentEvent e) {
		int width = e.getComponent().getWidth() ;
		int height = e.getComponent().getHeight() ;
		if(width < 250) {
			width = 250 ;
		}
		if(height < 530) {
			height = 500 ;
		}
		setSize(width, height) ;
	}

	public void componentMoved(ComponentEvent e) {

	}

	public void componentShown(ComponentEvent e) {

	}

	public void componentHidden(ComponentEvent e) {

	}
	
	private void initFriendList(){
		friendList.setModel(new DefaultTreeModel(
				new DefaultMutableTreeNode("JTree") {
					private static final long serialVersionUID = -7165711191622425567L;

					{
						Map<String, List<Object>> map = ClientContext.getValue(ClientConst.FRIENDS,Map.class) ;
						Iterator ite = map.entrySet().iterator() ;
						MyDefaultMutableTreeNode groupnode ;
						while(ite.hasNext()){
							Entry entry = (Entry) ite.next() ;
							String key = entry.getKey().toString() ;
							String[] group = key.split("#") ;
							JSONArray value = (JSONArray) entry.getValue();
							groupnode = new MyDefaultMutableTreeNode(group[1]) ;
							groupnode.setGroupId(group[0]) ;
							for(int i=0; i<value.size();i++){
								JSONArray o = (JSONArray) value.get(i);
								MyDefaultMutableTreeNode friend = new MyDefaultMutableTreeNode(
										o.get(1));
								friend.setUserId(o.get(0).toString());
								friend.setNickname(o.get(1).toString());
								friend.setImageUrl(o.getString(4)==null?"images/tangling.jpg":o.getString(4));
								groupnode.add(friend) ;
							}
							add(groupnode) ;
						}
					}
				}
				));
	}
	
	private void initChatGroupTree(){
		tree.setModel(new DefaultTreeModel(
				new DefaultMutableTreeNode("JTree") {
					private static final long serialVersionUID = 1604729191217443508L;

					{
						groupRootNode = new MyDefaultMutableTreeNode(
						"我的群");
						List<JSONObject> chatGroups = ClientContext.getValue(ClientConst.GROUPS,List.class) ;
						if(chatGroups!=null) {
							for(JSONObject cg : chatGroups) {
								addNode(cg,groupRootNode);
							}
						}
						add(groupRootNode) ;
					}
				}
		));
	}
	
	protected void addNode(JSONObject cg,DefaultMutableTreeNode root) {
		MyDefaultMutableTreeNode node = new MyDefaultMutableTreeNode(cg.get("groupName")) ;
		node.setOwnerId(cg.getString("ownerId")) ;
		node.setGroupId(cg.get("id").toString()) ;
		node.setImageUrl(cg.getString("iconPath")) ;
		node.setIsGroupNode(true);
		root.add(node);
	}
	
	public  void addNode(final JSONObject cg) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				DefaultTreeModel dm = (DefaultTreeModel) tree.getModel() ;
				MyDefaultMutableTreeNode root = (MyDefaultMutableTreeNode)((DefaultMutableTreeNode)dm.getRoot()).getFirstChild();
				MyDefaultMutableTreeNode node = new MyDefaultMutableTreeNode(cg.get("groupName")) ;
				node.setOwnerId(cg.getString("ownerId")) ;
				node.setGroupId(cg.get("id").toString()) ;
				node.setImageUrl(cg.getString("iconPath")) ;
				node.setIsGroupNode(true);
				dm.insertNodeInto(node, root, root.getChildCount());
				tree.revalidate();
			}
		});
	}
	
	public void showWindow(){
		initFriendList();
		initChatGroupTree();
		setVisible(true);
	}
	/**
	 * 给好友列表添加一个分组
	 * @param groupId
	 * @param groupName
	 */
	public void addGroup(String groupId, String groupName) {
		MyDefaultMutableTreeNode node = new MyDefaultMutableTreeNode(groupName) ;
		node.setGroupId(groupId) ;
		DefaultTreeModel model = (DefaultTreeModel)friendList.getModel();
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot() ;
		root.add(node) ;
		friendList.updateUI() ;
	}
	
	public void addFriend(String groupKey, JSONArray user,String remark) {
		String[] groupkey = groupKey.split("#") ;
		DefaultTreeModel model = (DefaultTreeModel)friendList.getModel() ;
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot() ;
		DefaultMutableTreeNode curNode = null ;
		Enumeration<MyDefaultMutableTreeNode> groups = (Enumeration<MyDefaultMutableTreeNode>) root.children() ;
		while(groups.hasMoreElements()) {
			MyDefaultMutableTreeNode group = groups.nextElement() ;
			if(groupkey[0].equals(group.getGroupId())) {
				curNode = group ;
			}
		}
		if(curNode!=null) {
			MyDefaultMutableTreeNode friend = new MyDefaultMutableTreeNode(remark) ;
			friend.setNickname(user.get(1).toString()) ;
			friend.setUserId(user.get(0).toString()) ;
			friend.setImageUrl(user.get(4).toString()) ;
			model.insertNodeInto(friend, curNode, curNode.getChildCount()) ;
		}

		friendList.revalidate();
	}
	
	@Override
	protected void hanlderCloseEvent() {
		ECPacket packet = new ECPacket() ;
		packet.setFrom(ClientContext.getLoginUser().getUserCode()) ;
		packet.setMessageType(ECMessageType.LOGOUT.name()) ;
		try {
			ClientContext.getContext().getClient().sendMessage(packet);
		} catch (Exception e) {
		}
		super.hanlderCloseEvent();
	}
	
	private void createAndShowChatWindow(MyDefaultMutableTreeNode node) {
		User user = new User() ;
		user.setNickName(node.getNickname()) ;
		user.setImagePath(node.getImageUrl()) ;
		user.setUserCode(node.getUserId()) ;
		Object obj = ClientContext.getValue(node.getUserId());
		Chat chat = null ;
		if(obj!=null && obj instanceof Chat){
			chat = (Chat)obj;
			chat.setState(JFrame.NORMAL);
		}else {
			chat = new Chat(user) ;
			ClientContext.putValue(node.getUserId(), chat);
			chat.setVisible(true);
		}
	}

}
